from django.db import transaction
from django.core.exceptions import ValidationError
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.views import APIView

from apps.projectbases.filters import ProjectPlanHFilters
from apps.projectbases.models import ProjectPlanHModel, ProjectInfoModel, ProjectCustomerModel, CommonSectionModel, \
    VersionHistoryModel, CommonSectionTypeModel
from apps.projectbases.serializers import ProjectPlanHSerializer, ProjectInfoSerializer, ProjectCustomerSerializer, \
    CommonSectionSerializer, VersionHistorySerializer, CommonSectionTypeSerializer
from bases.mixins import APIListModelMixin
from bases.viewsets import APIModelViewSet, APIReadOnlyViewSet
from utils.utils import update_instance, update_set
from bases.response import SuccessResponse


class ProjectPlanHViewSet(APIModelViewSet):
    # queryset = ProjectPlanHModel.objects.all()

    def get_queryset(self):
        current_user = self.request.user
        user_departments = current_user.departments.all()
        if user_departments:
            queryset = ProjectPlanHModel.objects.filter(departmentFK__in=user_departments)
        else:
            queryset = ProjectPlanHModel.objects.all()
        return queryset

    serializer_class = ProjectPlanHSerializer
    filter_class = ProjectPlanHFilters


    @transaction.atomic
    def perform_destroy(self, instance):
        if instance.project_status != 'O':
            raise ValidationError('状态不为O，不允许删除')

        VersionHistoryModel.objects.filter(projectPlanFK=instance).delete()  # 根据头表数据删除版本履历

        return super().perform_destroy(instance)

    @transaction.atomic
    @action(detail=True, methods=['put'])
    def release(self, request, *args, **kwargs):
        """
        该方法主要用来实现生效功能
        """
        instance = self.get_object()
        if instance.project_status != 'O':
            raise ValidationError('只有初始状态下的数据可以进行确认操作')
        instance.project_status = 'R'
        update_instance(instance, request)
        instance.save()
        return SuccessResponse()

    @transaction.atomic
    @action(detail=True, methods=['put'])
    def close(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.project_status != 'R':
            raise ValidationError('只有生效态下的数据可以进行关闭操作')
        instance.project_status = 'C'
        update_instance(instance, request)
        instance.save()
        return SuccessResponse()

class VersionHistoryViewSet(APIModelViewSet):
    queryset = VersionHistoryModel.objects.all()
    serializer_class = VersionHistorySerializer


class ProjectInfoViewSet(APIModelViewSet):

    def get_queryset(self):
        project_plan = self.request.GET.get('projectPlanFK')
        if project_plan:
            queryset = ProjectInfoModel.objects.filter(projectPlanFK__id=project_plan)
        else:
            queryset = ProjectInfoModel.objects.all()
        return queryset

    serializer_class = ProjectInfoSerializer


class ProjectCustomerViewSet(APIModelViewSet):

    def get_queryset(self):
        project_plan = self.request.GET.get('projectPlanFK')
        if project_plan:
            queryset = ProjectCustomerModel.objects.filter(projectPlanFK__id=project_plan)
        else:
            queryset = ProjectCustomerModel.objects.all()
        return queryset

    serializer_class = ProjectCustomerSerializer


class CommonSectionTypeViewSet(APIReadOnlyViewSet):
    """
    辅助信息类型视图
    """
    def get_queryset(self):
        section = self.request.GET.get('section')
        if section:
            queryset = CommonSectionTypeModel.objects.filter(section=section).order_by('id')
        else:
            queryset = CommonSectionTypeModel.objects.all().order_by('id')
        return queryset
    serializer_class = CommonSectionTypeSerializer


class CommonSectionTypeOnlyViewSet(APIReadOnlyViewSet):
    """
    按照辅助信息的类型进行分组，只获取辅助信息类型数据
    """
    queryset = CommonSectionTypeModel.objects.values('section').distinct().order_by('section')
    serializer_class = CommonSectionTypeSerializer

class CommonSectionViewSet(APIModelViewSet):
    """
    辅助信息视图
    """
    def get_queryset(self):
        project_plan = self.request.GET.get('projectPlanFK')
        if project_plan:
            # queryset = CommonSectionModel.objects.filter(projectPlanFK__id=project_plan).select_related('sectionFK').values('sectionFK__section', 'sectionFK__section_item','value')
            queryset = CommonSectionModel.objects.filter(projectPlanFK__id=project_plan).select_related('sectionFK').order_by('id')
        else:
            queryset = CommonSectionModel.objects.all()
        return queryset

    serializer_class = CommonSectionSerializer

    @transaction.atomic
    @action(detail=False, methods=['get'])
    def get_groupbysection(self, request):
        project_plan = self.request.GET.get('projectPlanFK')
        sections = CommonSectionModel.objects.filter(projectPlanFK_id=project_plan).select_related('sectionFK').order_by('sectionFK__id')
        grouped_data = {}
        for item in sections:
            section_name = item.sectionFK.section
            if section_name not in grouped_data:
                grouped_data[section_name] = []

            grouped_data[section_name].append({
                'section_item': item.sectionFK.section_item,
                'value': item.value
            })
        return SuccessResponse(grouped_data)

    @transaction.atomic
    @action(detail=False, methods=['post'])
    def batch_create(self, request):
        """批量更新：根据前端传来的项目计划ID，在辅助信息类型表中获取全部数据，然后批量创建数据"""
        projectPlanid = request.data.get('projectPlanFK')
        try:
            # 使用 get 方法获取单个 ProjectPlanHModel 实例
            project_plan_instance = ProjectPlanHModel.objects.get(id=projectPlanid)
        except ProjectPlanHModel.DoesNotExist:
            raise ValidationError(f'项目计划ID{projectPlanid}, 在系统中不存在')

        items = request.data.get('itemlist')
        for item_data in items:
            section = item_data.get('section')
            value = item_data.get('value')
            section_instance = CommonSectionTypeModel.objects.get(id=section)

            CommonSectionModel.objects.create(
                projectPlanFK = project_plan_instance,
                sectionFK = section_instance,
                value=value,
                **update_set(request, True)
            )

        return SuccessResponse()


    @transaction.atomic
    @action(detail=False, methods=['put'])
    def batch_update(self, request):
        """批量更新：前端传section+多个{item: value}"""
        projectPlanid = request.data.get('projectPlanFK')
        items = request.data.get('itemlist')
        for item_data in items:
            section = item_data.get('section')
            value = item_data.get('value')
            result = CommonSectionModel.objects.filter(projectPlanFK__id=projectPlanid, sectionFK__id=section)
            if result:
                result.update(value=value,**update_set(request, False))
            else:
                raise ValidationError(f'项目计划ID{projectPlanid},Section:{section}, 在系统中不存在')
        return SuccessResponse()

    @transaction.atomic
    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        """
        该方法用于批量删除功能，前端返回一个由id构成的数组，后端进行for循环删除
        """
        projectplanid = request.data.get('projectPlanFK')
        query = CommonSectionModel.objects.filter(projectPlanFK__id=projectplanid)
        query.delete()

        return SuccessResponse()


class MoreSectionViewSet(APIModelViewSet):
    """前端传项目计划书ID，后端查询这个项目计划书ID下的所有数据，只是在前端可以过滤掉想要过滤的数据"""
    def get_queryset(self):
        project_plan = self.request.GET.get('projectPlanFK')

        if project_plan:
            queryset = CommonSectionModel.objects.filter(projectPlanFK__id=project_plan).order_by('id')
        else:
            queryset = CommonSectionModel.objects.all().order_by('id')
        return queryset

    serializer_class = CommonSectionSerializer

    @transaction.atomic
    @action(detail=False, methods=['post'])
    def moreSectionCreate(self, request):
        """批量更新：前端传多个section+多个{item: value}"""
        section_list = request.data
        for section_data in section_list:
            section = section_data.get('section')
            projectPlanid = section_data.get('projectPlanFK')
            try:
                # 使用 get 方法获取单个 ProjectPlanHModel 实例
                project_plan_instance = ProjectPlanHModel.objects.get(id=projectPlanid)
            except ProjectPlanHModel.DoesNotExist:
                raise ValidationError(f'项目计划ID{projectPlanid}, 在系统中不存在')

            items = section_data.get('itemlist')
            for item_data in items:
                item = item_data.get('item')
                value = item_data.get('value')

                CommonSectionModel.objects.create(
                    projectPlanFK=project_plan_instance,
                    section=section,
                    item=item,
                    value=value,
                    **update_set(request, True)
                )

        return SuccessResponse()

    @transaction.atomic
    @action(detail=False, methods=['put'])
    def moreSectionUpdate(self, request):
        """批量更新：前端传多个section+多个{item: value}"""
        seltionlist = request.data.get('seltionlist')
        for seltion_data in seltionlist:
            section = seltion_data.get('section')
            projectPlanid = seltion_data.get('projectPlanFK')
            items = seltion_data.get('itemlist')
            for item_data in items:
                item = item_data.get('item')
                value = item_data.get('value')
                result = CommonSectionModel.objects.filter(projectPlanFK__id=projectPlanid, section=section, item=item)
                if result:
                    result.update(value=value, **update_set(request, False))
                else:
                    raise ValidationError(f'项目计划ID{projectPlanid},Section:{section},Item:{item}, 在系统中不存在')
        return SuccessResponse()